package netty.nio;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Date;
import java.util.Iterator;
import java.util.Set;

/**
 * @program NettyLeaning
 * @description:
 * @author: zhanglu
 * @create: 2022-01-16 22:25:00
 */
@Slf4j
public class TimeServerClient {

    private static final String IP = "127.0.0.1";
    private static final Integer PORT = 8080;

    /**************************服务端**************************/

    @Test
    public void server() throws Exception {
        //出实话多路复用器，绑定监听端口
        Selector selector = Selector.open();
        ServerSocketChannel serverChannel = ServerSocketChannel.open();
        serverChannel.configureBlocking(false);//非阻塞
        serverChannel.socket().bind(new InetSocketAddress(PORT), 1024);
        serverChannel.register(selector, SelectionKey.OP_ACCEPT);
        log.info("server is start port : " + PORT);
        boolean stop = false;
        while (!stop){
            try {
                selector.select(1000);
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator<SelectionKey> it = selectionKeys.iterator();
                SelectionKey key = null;
                while (it.hasNext()){
                    key = it.next();
                    it.remove();
                    try {
                        serverHandleInput(selector, key);
                    } catch (Exception e){
                        if(key != null){
                            key.cancel();
                            if(key.channel() != null){
                                key.channel().close();
                            }
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if(selector != null){
            try {
                selector.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 处理新接入的消息
     * @param key
     * @throws Exception
     */
    public void serverHandleInput(Selector selector, SelectionKey key) throws Exception{
        if (key.isValid()){
           if(key.isAcceptable()){
               ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();
               SocketChannel channel = serverSocketChannel.accept();
               channel.configureBlocking(false);
               channel.register(selector, SelectionKey.OP_READ);
           }
            if(key.isReadable()){
                SocketChannel channel = (SocketChannel) key.channel();
                this.serverBusiness(channel, key);
            }
        }
    }

    public void serverBusiness(SocketChannel sc, SelectionKey key) throws Exception{
        ByteBuffer readBuffer = ByteBuffer.allocate(1024);
        int readBytes = sc.read(readBuffer);
        if(readBytes > 0){
            readBuffer.flip();
            byte[] bytes = new byte[readBuffer.remaining()];
            readBuffer.get(bytes);
            String body = new String(bytes, CharsetUtil.UTF_8);
            log.info("server receive : " + body);
            String currentTime = DateUtil.formatDateTime(new Date());
            byte[] bodyBytes = currentTime.getBytes();
            ByteBuffer writeBuffer = ByteBuffer.allocate(bodyBytes.length);
            writeBuffer.put(bodyBytes);
            writeBuffer.flip();
            sc.write(writeBuffer);
        }else if(readBytes < 0){
            //对端链路关闭
            key.channel();
            sc.close();
        }else {
            //读到0字节，忽略
        }
    }

    /**************************客户端**************************/

    @Test
    public void client() throws Exception{
        boolean stop = false;
        Selector selector = Selector.open();
        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.configureBlocking(false);
        //如果直接连接成功，则注册到多路复用器上，发送请求消息，读应答
        if(socketChannel.connect(new InetSocketAddress(IP, PORT))){
            log.info("client connected...");
            socketChannel.register(selector, SelectionKey.OP_READ);
            clientBusiness(socketChannel);
        }else {
            log.info("client connect...");
            socketChannel.register(selector, SelectionKey.OP_CONNECT);
        }
        while (!stop){
            selector.select(1000);
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> it = selectionKeys.iterator();
            SelectionKey key = null;
            while (it.hasNext()){
                key = it.next();
                it.remove();
                try {
                    clientHandleInput(selector, key);
                } catch (Exception e) {
                    e.printStackTrace();
                    if(key != null){
                        key.channel();
                        if(key.channel() != null){
                            key.channel().close();
                        }
                    }
                }

            }
        }
        if(selector != null){
            selector.close();
        }
    }

    public void clientHandleInput(Selector selector , SelectionKey key) throws Exception{
        if(key.isValid()){
            SocketChannel channel = (SocketChannel) key.channel();
            if(key.isConnectable()){
                if(channel.finishConnect()){
                    channel.register(selector, SelectionKey.OP_READ);
                    clientBusiness(channel);
                }else{
                    System.exit(1);
                }
            }
            if(key.isReadable()){
                ByteBuffer readBuffer = ByteBuffer.allocate(1024);
                int readBytes = channel.read(readBuffer);
                if(readBytes > 0){
                    readBuffer.flip();
                    byte[] bytes = new byte[readBuffer.remaining()];
                    readBuffer.get(bytes);
                    String body = new String(bytes, CharsetUtil.UTF_8);
                    log.info(body);
                    System.exit(1);
                }else if(readBytes < 0){
                    //对端链路关闭
                    key.channel();
                    channel.close();
                }else {
                    //读到0字节，忽略
                }
            }
        }
    }

    public void clientBusiness(SocketChannel channel) throws Exception{
        byte[] req = "client handler".getBytes();
        ByteBuffer writeBuffer = ByteBuffer.allocate(req.length);
        writeBuffer.put(req);
        writeBuffer.flip();
        channel.write(writeBuffer);
        if(!writeBuffer.hasRemaining()){
            log.info("send server success.");
        }
    }

}
